package com.ygo.feihua;
import android.annotation.*;
import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import android.support.v7.widget.Toolbar;

import java.io.*;
import java.util.*;
import android.webkit.*;
/*
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.sdk.DownloadListener;
*/
public class Web extends AppCompatActivity
{
	private WebView webView;
	private ProgressBar web_pro;
	private Toolbar tool;
	
	private Gongju gj;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO: Implement this method
		super.onCreate(savedInstanceState);
		setContentView(R.layout.web_view);
		webView=(WebView) findViewById(R.id.webview);
		gj=Gongju.getdx(this);
		Intent intent=getIntent();
        String wz=intent.getStringExtra("wz");
		 tool=(Toolbar) findViewById(R.id.toolbar);
		web_pro=(ProgressBar) findViewById(R.id.web_pro);
		
		web_pro.setMax(100);
		web_pro.setVisibility(View.GONE);
		gj.cshToolbar(tool,"网址");
		
		//设置是否支持变焦
		webView.getSettings().setSupportZoom(true);
		//设置是否支持JavaScript
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setBuiltInZoomControls(true);//设置是否支持缩放
		webView.getSettings().setUseWideViewPort(true);
		//webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		//webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webView.getSettings().setLoadWithOverviewMode(true);
		webView.getSettings().setAppCacheEnabled(true);
		webView.getSettings().setDomStorageEnabled(true);
		webView.requestFocus();
		
		webView.setWebChromeClient(new WebChromeClient() 
			{

				public void onProgressChanged(WebView view, int progress) {   	
					if (progress != 100) {
						web_pro.setProgress(progress);
						web_pro.setVisibility(View.VISIBLE);
						tool.setTitle("网址加载中");
					} else {				
						web_pro.setVisibility(view.GONE);	
						tool.setTitle(view.getTitle());
					}
				}

				//WebChromeClient的几个方法：
				public void openFileChooser(ValueCallback<Uri> uploadMsg) {  
					mUploadMessage = uploadMsg;  
					Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
					i.addCategory(Intent.CATEGORY_OPENABLE);  
					i.setType("*/*");  
					startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);  
				}
				public void openFileChooser(ValueCallback uploadMsg, String acceptType) {  
					this.openFileChooser(uploadMsg);
				}

				public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {  
					this.openFileChooser(uploadMsg);
				}

				// For Android 5.0+  
				public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {  
					mUploadCallbackAboveL = filePathCallback;  
					Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
					i.addCategory(Intent.CATEGORY_OPENABLE);  
					i.setType("*/*");  
					startActivityForResult(  
						Intent.createChooser(i, "File Browser"),  
						FILECHOOSER_RESULTCODE);  
					return true;  
				}  


			});    
		
		webView.loadUrl(wz);
		
		webView.setWebViewClient(new WebViewClient(){
				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					if(url == null) 
						return false;
					try {
						if(url.startsWith("weixin://") || url.startsWith("alipays://") ||
						   url.startsWith("mailto://") || url.startsWith("tel://")||url.startsWith("tbfrs://")
						   ||url.startsWith("tbopen://")
						//其他自定义的scheme
							) {
							Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
							startActivity(intent);
							return true;
						}
					} catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
						return false;
					}
					//处理http和https开头的url
					view.loadUrl(url);
					return true;
				}
			});
// 设置web视图客户端
		//webView.setWebViewClient(new MyWebViewClient());
		//webView.setDownloadListener(new MyWebViewDownLoadListener());
		
		/*
		 （1）setAllowFileAccess(boolean allow); 　　　　　　//设置启用或禁止访问文件数据
		 　　（2）setBuiltInZoomControls(boolean enabled); 　　//设置是否支持缩放
		 　　（3）setDefaultFontSize(int size);  　　　　　　　　  //设置默认的字体大小
		 　　（4）setJavaScriptEnabled(boolean flag); 　　　　　 //设置是否支持JavaScript
		 　　（5）setSupportZoom(boolean support); 　　　　　　//设置是否支持变焦
		 3.WebViewClient
		
		
		*/
		webView.setDownloadListener(new DownloadListener(){

				@Override
				public void onDownloadStart(String p1, String p2, String p3, String p4, long p5)
				{
					
					
				//	xiazai(p1,"废话.apk");
					Uri uri = Uri.parse(p1);  
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);  
					startActivity(intent);  
					
					
					//Log.e("内容为","内容为"+p1+"\n"+p2+"\n"+p3+"\n"+p4+"\n"+p5);
				/*	//p1为uri,p2为设备信息,p3为文件名,p4为文件类型,p5为大小,单位byte
					String s=p3;
					//String s=p3.substring(p3.indexOf("attachment;filename=\"",p3.length()-2));
					String ss=p3;
						
					try
					{
						String  ap=new String(ss.getBytes("ISO8859_1"), "gb2312");
						Log.e("转换成功","成功了"+ap);
					}
					catch (UnsupportedEncodingException e)
					{
						
						Log.e("转换失败","原因为"+e);
					}

					*/
					
					
					
						/*
					FileDownloader.getImpl().create(p1)
						.setPath(gj.path_gen+"ygo助手/下载/")
						.setListener(new FileDownloadListener() {
							@Override
							protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
								t.setText("准备下载中");
							}
							@Override
							protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
							}
							@Override
							protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
								
								t.setText("正在下载"+soFarBytes+"废话"+totalBytes);
							}
							@Override
							protected void blockComplete(BaseDownloadTask task) {
							}
							@Override
							protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
							}
							@Override
							protected void completed(BaseDownloadTask task) {
								gj.dis();
								gj.show("下载成功");
							}
							@Override
							protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
							}
							@Override
							protected void error(BaseDownloadTask task, Throwable e) {
								gj.dis();
								gj.show("下载错误"+e);
							}
							@Override
							protected void warn(BaseDownloadTask task) {
							}
						}).start();
						
						*/
					/*	
					View[] v=gj.dialogj(true,p3,"准备下载,请稍等");
					Button b=(Button) v[0];
					final TextView t=(TextView) v[1];
					b.setText("取消");
					b.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View p1)
							{
								gj.dis();
								// TODO: Implement this method
							}
						});
						
						String filenane="";
						
					BmobFile bf=new BmobFile(filenane,"",p1);
					bf.download(new File(gj.PATH_OURYGO+"download/"+filenane), new DownloadFileListener(){

							@Override
							public void done(String p1, BmobException p2)
							{
								if(p2==null){
									gj.dis();
									gj.dialogt(false,"","成功下载到"+p1+"\n是否解压这个资源包？");
								}else{
									gj.dis();
									gj.show("下载失败"+p2);
								}
								// TODO: Implement this method
							}

							@Override
							public void onProgress(Integer p1, long p2)
							{
								t.setText("正在下载"+p1+"%");
								// TODO: Implement this method
							}
						});
					*/
					
					
					// TODO: Implement this method
				}
			});
		
		}
	private static final int FILECHOOSER_RESULTCODE = 0;
	private ValueCallback<Uri[]> mUploadCallbackAboveL;
	private ValueCallback<Uri> mUploadMessage;          
	
	
//Activity的方法：
	@Override  
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		super.onActivityResult(requestCode, resultCode, data);  
		if(requestCode==FILECHOOSER_RESULTCODE)  
		{  
			if (null == mUploadMessage && null == mUploadCallbackAboveL) 
				return;  
			Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();  
			if (mUploadCallbackAboveL != null) {  
				onActivityResultAboveL(requestCode, resultCode, data);  
			}else if(mUploadMessage != null) {  
				mUploadMessage.onReceiveValue(result);  
				mUploadMessage = null;  
			}  
		}  
	}    
	
	@TargetApi(Build.VERSION_CODES.LOLLIPOP)  
	private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {  
		if (requestCode != FILECHOOSER_RESULTCODE  
            || mUploadCallbackAboveL == null) {  
			return;  
		}  
		Uri[] results = null;  
		if (resultCode == Activity.RESULT_OK) {  
			if (data != null){  
				String dataString = data.getDataString();  
				ClipData clipData = data.getClipData();  
				if (clipData != null) {  
					results = new Uri[clipData.getItemCount()];  
					for (int i = 0; i < clipData.getItemCount(); i++) {  
						ClipData.Item item = clipData.getItemAt(i);  
						
						results[i] = item.getUri();  
					}  
				}  
				
				if (dataString != null)  
					results = new Uri[]{Uri.parse(dataString)};  
			}  
		}  
		mUploadCallbackAboveL.onReceiveValue(results);  
		mUploadCallbackAboveL = null;  
		return;  
	}
		
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// TODO: Implement this method
		getMenuInflater().inflate(R.menu.menu_web, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO: Implement this method
		switch(item.getItemId()){
			case R.id.web_tz:
				startActivity(new Intent (Intent.ACTION_VIEW,Uri.parse(webView.getUrl())));
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	
		
		
	 
}
